import router from "./router"
import store from "./store"
import NProgress from "nprogress"
import { Message } from "element-ui"
import "nprogress/nprogress.css"
import getPageTitle from "@/utils/get-page-title"

router.beforeEach(async (to, from, next) => {
    NProgress.start()
    // 设置页面标题
    document.title = getPageTitle(to.meta.title)
    // 获取用户信息
    const userInfo = store.getters.user
    if (to.meta.auth) {
        if (userInfo) {
            next()
        } else {
            const token = localStorage.getItem("token")
            if (token) {
                try {
                    await store.dispatch("user/getInfo")
                    next()
                    NProgress.done()
                } catch (err) {
                    await store.dispatch("user/resetToken")
                    Message.error("认证过期，请重新登录")
                    next(`login?redirect=${to.path}`)
                    NProgress.done()
                }
            } else {
                next(`login?redirect=${to.path}`)
                NProgress.done()
            }
        }
    } else {
        if (to.path === "/login" && userInfo) {
            next()
            NProgress.done()
        } else {
            next()
            NProgress.done()
        }
    }
})

router.afterEach(() => {
    NProgress.done()
})
